package Sort;


import java.util.Arrays;

public class HeapSort {
    public static void main(String[] args) {
        int[] arr = {1,10,7,4,8,3,2,6,9,5};
        Heap heap = new Heap(arr);
        System.out.println(Arrays.toString(arr));
    }

}

class Heap {
    int[] arr;
    int size = 0;

    public Heap(int[] arr) {
        this.arr = arr;
        this.size = arr.length;
        buildBigHeap(arr,size);
        heapSort(arr);
    }

    public void buildBigHeap(int[] arr,int size) {
        for (int i = size / 2 - 1; i >= 0 ; i--) {
            down(i,size);
        }
    }
    private void down(int i,int size) {
        int left = i * 2 + 1;
        int right = left + 1;
        int max = i;
        if (left < size && arr[max] < arr[left]) {
            max = left;
        }
        if (right < size && arr[max] < arr[right]) {
            max = right;
        }
        if (max != i) {
            swap(arr,max,i);
            down(max,size);
        }

    }
    private void swap(int[] arr,int i,int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

    public void heapSort(int[] arr) {
        for (int i = arr.length - 1; i > 0 ; i--) {
            swap(arr,i,0);
            down(0,i);
        }
    }

}

